package com.example.movie

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.movie.entity.MovieTypeEntity
import com.blankj.utilcode.util.ToastUtils
import com.example.base.RouterPath
import com.example.common.mvi.BaseMviFragment
import com.example.movie.adapter.MovieViewPagerAdapter
import com.example.movie.databinding.FragmentMovieBinding
import com.example.movie.intent.MovieViewIntent
import com.example.movie.state.MovieUiState
import com.example.movie.vm.MovieViewModel
import com.google.android.material.tabs.TabLayoutMediator
import com.lxj.xpopup.XPopup
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = RouterPath.PATH_FRAGMENT_MOVIE)
class MovieFragment : BaseMviFragment<FragmentMovieBinding>() {

    private val search = arrayListOf("萝莉","御姐","甜妹","清纯","可爱","活泼")

    private val mViewModel : MovieViewModel by activityViewModels()

    //一级分类集合
    private var oneTypeList = mutableListOf<MovieTypeEntity>()
    //二级分类集合
    private var twoTypeList = mutableListOf<MovieTypeEntity>()

    private lateinit var mXPopupBuilder:XPopup.Builder

    private var leverOneTypeId:Int = 1

    private lateinit var mViewPageAdapter:MovieViewPagerAdapter
    private var fragment = mutableListOf<MovieListFragment>()

    override fun initViews() {
        mDataBinding.tbvSearch.setDatas(search)

        //筛选的Popup
        mXPopupBuilder = XPopup.Builder(requireContext()).atView(mDataBinding.cltFilter)

        //筛选的点击事件
        mDataBinding.tvFilter.setOnClickListener{
            showMovieTypeFilter()
        }


        mViewPageAdapter = MovieViewPagerAdapter(fragment,this@MovieFragment.childFragmentManager,lifecycle)
        mDataBinding.vpVideo.offscreenPageLimit = 4
        mDataBinding.vpVideo.adapter = mViewPageAdapter

        //关联TabLayout和ViewPage2
        TabLayoutMediator(mDataBinding.tabTypeLayout,mDataBinding.vpVideo){tab,position->
            tab.text = twoTypeList[position].typename
        }.attach()
    }
    private fun showMovieTypeFilter(){

        if(oneTypeList.isNotEmpty()){
            var menuNameList = mutableListOf<String>()
            oneTypeList.forEach{
                menuNameList.add(it.typename)
            }
            mXPopupBuilder.asAttachList(menuNameList.toTypedArray(),null){positoins,_,->

                leverOneTypeId = oneTypeList[positoins].id

                //发送新的二级分类意图
                loadNewTwoTypeById()
            }.show()

        }


    }
    private fun loadNewTwoTypeById(){
       lifecycleScope.launch {
           mViewModel.channel.send(MovieViewIntent.LoadLevelTwoType(leverOneTypeId))
       }
    }

    override fun getLayoutId(): Int =R.layout.fragment_movie

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(MovieViewIntent.LoadLevelOneType)
        mViewModel.channel.send(MovieViewIntent.LoadLevelTwoType(leverOneTypeId))
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is MovieUiState.LoadLeverOneTypeSuccess -> initLeverOneTypePopupWindow(it.list)
                is MovieUiState.LoadLevelOneTypeFail -> ToastUtils.showLong("一级分类获取失败")
                is MovieUiState.LoadLeverTwoTypeSuccess -> initLeverTwoLayout(it.list)
                is MovieUiState.LoadLeverTwoTypeFail -> loadNewTwoFail()
                else->{}
            }
        }
    }

    private fun loadNewTwoFail(){
        twoTypeList.clear()
        fragment.clear()
        mDataBinding.tabTypeLayout.removeAllTabs()

        //添加推荐Tab实体
        twoTypeList.add(MovieTypeEntity("", 0, -1, 0,"tuijian", "推荐"))
        fragment.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId", -1).navigation() as MovieListFragment)

        //Tab标签设置
        twoTypeList.forEach {
            mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename))
        }

        //重置适配器，防止缓存导致页面展示与分类不匹配问题（非常重要）
        mDataBinding.vpVideo.adapter = mViewPageAdapter
        //更新UI数据
        mViewPageAdapter.notifyDataSetChanged()
    }

    private fun initLeverOneTypePopupWindow(list:List<MovieTypeEntity>){
        if(oneTypeList.size > 0){
            oneTypeList.clear()
        }
        oneTypeList.addAll(list)
    }
    private fun initLeverTwoLayout(list:List<MovieTypeEntity>){
        if(list.isNotEmpty()){
            twoTypeList.clear()
            fragment.clear()

            mDataBinding.tabTypeLayout.removeAllTabs()
            //添加推荐Tab实体
            twoTypeList.add(MovieTypeEntity("",0,-1,0,"tuijian","推荐"))
            fragment.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId",-1).navigation()as MovieListFragment)

            list.forEach{
                twoTypeList.add(it)
                fragment.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MOVIE_LIST).withInt("tabId", it.id).navigation() as MovieListFragment)
            }
            //创建Tab组件,并添加到分类布局容器中
            twoTypeList.forEach{
                mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename))
            }

            //重置适配器，防止分类重复
            mDataBinding.vpVideo.adapter = mViewPageAdapter
            mViewPageAdapter.notifyDataSetChanged()
        }


    }

}